<template>
  <div class="student-schedule">
    <el-card class="filter-card" shadow="hover">
      <div class="filter-form">
        <el-form :model="filterForm" inline>
          <el-form-item label="学年">
            <el-select v-model="filterForm.academicYear" placeholder="请选择学年" style="width: 150px">
              <el-option label="2023-2024" value="2023-2024"></el-option>
              <el-option label="2024-2025" value="2024-2025"></el-option>
              <el-option label="2025-2026" value="2025-2026"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="周次">
            <el-select v-model="filterForm.weekNumber" placeholder="请选择周次" style="width: 120px">
              <el-option 
                v-for="week in 20" 
                :key="week" 
                :label="`第${week}周`" 
                :value="week">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="loadSchedule" :loading="loading">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card class="schedule-card" shadow="hover" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>我的课程表</span>
          <div class="header-info" v-if="filterForm.weekNumber">
            <span>{{ filterForm.academicYear }} 第{{ filterForm.weekNumber }}周</span>
          </div>
        </div>
      </template>

      <div class="schedule-container" v-if="filterForm.weekNumber">
        <div class="schedule-grid">
          <!-- 表头 -->
          <div class="grid-header">
            <div class="time-header">时间</div>
            <div class="day-header" v-for="day in weekDays" :key="day.value">
              {{ day.label }}
            </div>
          </div>

          <!-- 时间段行 -->
          <div 
            v-for="timeSlot in timeSlots" 
            :key="timeSlot.timeSlot" 
            class="grid-row"
          >
            <div class="time-cell">
              <div class="time-slot">第{{ timeSlot.timeSlot }}节</div>
              <div class="time-range">{{ timeSlot.startTime }}-{{ timeSlot.endTime }}</div>
            </div>
            
            <div 
              v-for="day in weekDays" 
              :key="day.value"
              class="schedule-cell"
            >
              <div 
                v-if="getCellCourse(timeSlot.timeSlot, day.value)"
                class="course-item"
              >
                <div class="course-name">{{ getCellCourse(timeSlot.timeSlot, day.value).courseName }}</div>
                <div class="teacher-name">{{ getCellCourse(timeSlot.timeSlot, day.value).teacherName }}</div>
                <div class="class-name">{{ getCellCourse(timeSlot.timeSlot, day.value).className }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-state">
        <el-empty description="请选择学年和周次查看课程表" />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import scheduleApi from '../../api/schedule'
import { useUserStore } from '../../stores/user'

const loading = ref(false)
const filterForm = reactive({
  academicYear: '2024-2025',
  weekNumber: null
})

const weekDays = [
  { label: '周一', value: 1 },
  { label: '周二', value: 2 },
  { label: '周三', value: 3 },
  { label: '周四', value: 4 },
  { label: '周五', value: 5 },
  { label: '周六', value: 6 },
  { label: '周日', value: 7 }
]

const timeSlots = ref([])
const scheduleData = ref({})

// 加载时间段
const loadTimeSlots = async () => {
  try {
    const response = await scheduleApi.getAllTimeSlots()
    if (response.code === 200) {
      timeSlots.value = response.data || []
    }
  } catch (error) {
    console.error('获取时间段配置失败:', error)
    ElMessage.error('获取时间段配置失败')
  }
}

// 加载课程表
const loadSchedule = async () => {
  if (!filterForm.weekNumber) {
    ElMessage.warning('请先选择周次')
    return
  }
  
  loading.value = true
  try {
    console.log('=== 前端学生课表查询 ===')
    console.log('查询参数:', {
      academicYear: filterForm.academicYear,
      weekNumber: filterForm.weekNumber
    })
    
    // 添加用户信息检查
    const userStore = useUserStore()
    console.log('当前用户信息:', userStore.currentUser)
    console.log('用户ID:', userStore.currentUser?.id)
    console.log('用户角色:', userStore.currentUser?.roles)
    
    const response = await scheduleApi.getCurrentStudentWeeklySchedule(
      filterForm.academicYear, 
      filterForm.weekNumber
    )
    
    console.log('API响应:', response)
    
    if (response.code === 200) {
      scheduleData.value = response.data || {}
      console.log('课表数据:', scheduleData.value)
      
      // 统计课程数量
      let totalCourses = 0
      Object.keys(scheduleData.value).forEach(day => {
        const daySchedule = scheduleData.value[day] || []
        totalCourses += daySchedule.length
        console.log(`星期${day}: ${daySchedule.length}门课程`, daySchedule)
      })
      console.log('总课程数量:', totalCourses)
      
      if (totalCourses === 0) {
        console.log('没有找到课程表数据')
        ElMessage.info('该周暂无课程安排')
      } else {
        ElMessage.success(`成功加载${totalCourses}门课程`)
      }
      
    } else {
      console.error('API返回错误:', response.message)
      ElMessage.error(response.message || '获取课程表失败')
    }
  } catch (error) {
    console.error('获取课程表失败:', error)
    ElMessage.error('获取课程表失败')
  } finally {
    loading.value = false
  }
}

// 获取单元格课程
const getCellCourse = (timeSlot, dayOfWeek) => {
  const dayKey = String(dayOfWeek)
  const daySchedules = scheduleData.value[dayKey] || []
  return daySchedules.find(s => s.timeSlot === timeSlot)
}

// 页面加载时执行
onMounted(() => {
  loadTimeSlots()
  // 设置默认为当前周（这里简化为第1周）
  filterForm.weekNumber = 1
  loadSchedule()
})
</script>

<style scoped>
.student-schedule {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  align-items: center;
  gap: 20px;
}

.schedule-card {
  min-height: 600px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-info {
  color: #606266;
  font-size: 14px;
}

.schedule-container {
  overflow-x: auto;
}

.schedule-grid {
  min-width: 800px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.grid-header {
  display: grid;
  grid-template-columns: 120px repeat(7, 1fr);
  background-color: #f5f7fa;
}

.time-header, .day-header {
  padding: 15px 10px;
  text-align: center;
  font-weight: 600;
  border-right: 1px solid #e4e7ed;
}

.day-header:last-child {
  border-right: none;
}

.grid-row {
  display: grid;
  grid-template-columns: 120px repeat(7, 1fr);
  border-top: 1px solid #e4e7ed;
}

.time-cell {
  padding: 10px;
  background-color: #fafafa;
  border-right: 1px solid #e4e7ed;
  text-align: center;
}

.time-slot {
  font-weight: 600;
  color: #303133;
  margin-bottom: 5px;
}

.time-range {
  font-size: 12px;
  color: #909399;
}

.schedule-cell {
  border-right: 1px solid #e4e7ed;
  min-height: 80px;
  position: relative;
}

.schedule-cell:last-child {
  border-right: none;
}

.course-item {
  padding: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 4px;
  margin: 4px;
  height: calc(100% - 8px);
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.course-name {
  font-weight: 600;
  font-size: 14px;
  margin-bottom: 4px;
  line-height: 1.2;
}

.teacher-name {
  font-size: 12px;
  opacity: 0.9;
  margin-bottom: 2px;
}

.class-name {
  font-size: 11px;
  opacity: 0.8;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .schedule-grid {
    min-width: 600px;
  }
  
  .grid-header, .grid-row {
    grid-template-columns: 80px repeat(7, 1fr);
  }
  
  .time-cell {
    padding: 5px;
  }
  
  .course-item {
    padding: 4px;
  }
  
  .course-name {
    font-size: 12px;
  }
  
  .teacher-name, .class-name {
    font-size: 10px;
  }
}
</style> 